<template>
  <div class="cart">
    <!-- 购物车头部 -->
    <!--头部区域-->
    <header class="title-wrapper">
      <h4><strong>购物车</strong></h4>
      <div
        class="clearCart"
        :style="selectedGoodsCount === 0 ? 'color: grey': 'color: red'"
        @click="clearCart"
        v-show="isShowEmptyCart">
        <span>删除</span>
      </div>
    </header>
    <!-- 购物车没有商品 -->
    <div class="cart-wrapper">
      <!-- 购物车为空 -->
      <div class="emptyCart" v-show="!isShowEmptyCart">
        <img src="@/assets/img/cart/empty.png" alt="">
        <div class="title"><span>购物车空空如也~</span></div>
          <router-link class="goHome" to="/dashboard/home"><span>去逛逛</span> </router-link>
      </div>
      <!-- 购物车有数据 -->
      <div class="contentWrapper" v-show="isShowEmptyCart">
        <div
          class="contentWrapperList"
          v-for="goods in shopCart"
          :key="goods.id"
        >
          <section>
            <div class="shopCartListCon">
              <div class="left">
                <a
                  href="javaScript:;"
                  class="cartCheckBox"
                  :checked="goods.checked"
                  @click.stop="single(goods.id)"
                >
                </a>
              </div>
              <div class="center">
                <img :src="goods.smallImage">
              </div>
              <div class="right">
                <a>{{goods.name}}</a>
                <div class="bottomContent">
                  <p class="shopPrice"> ￥{{goods.price}}</p>
                  <div class="shopDeal">
                    <span @click="reduceGoods(goods.id, goods.num)">-</span>
                    <input type="number"
                           disabled
                           v-model="goods.num">
                    <span
                      @click="addGoods(goods.id, goods.name, goods.smallImage, goods.price)">+</span>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
        <!-- 提交订单 -->
        <van-submit-bar
          :price="totalPrice"
          :button-text="submitBtn"
          @submit="onSubmit"
          :disabled="!(selectedGoodsCount > 0)"
          v-show="isShowEmptyCart"
        >
          <van-checkbox v-model="isCheckedAll" checked-color='#45c763'>
            <span>全选</span>
          </van-checkbox>
        </van-submit-bar>
      </div>

      <!-- 猜你喜欢 -->
      <van-divider :style="guessYouLike">猜你喜欢</van-divider>

      <!-- 商品详情组件 需要注意下底部是否被遮盖 动态设置padding-bottom -->
      <product-item :productList="youLike_product_lists"
                   :style="isShowEmptyCart?'padding-bottom: 1.28rem':'padding-bottom: 1.02rem'" />
    </div>
    <!-- <Loading :show="isShowLoading" /> -->
    <!-- 回到顶部组件 -->
    <back-to-top />
  </div>
</template>

<script>
import ProductItem from '@/components/content/home/TabBarItemList'

import { getGuessYouLike } from '../../network/home'
import { mapMutations, mapGetters } from 'vuex'
import { getLocalStore } from '../../config/global'

export default {
  name: 'Cart',
  mounted () {
    // 初始化数据
    this._initData()
  },
  data () {
    return {
      youLike_product_lists: [],
      isShowLoading: false,
      isEmptyCart: false,
    }
  },
  components: {
    ProductItem
    // Loading
  },
  computed: {
    // 猜你喜欢
    guessYouLike () {
      return {
        color: '#000',
        borderColor: 'grey',
        padding: '0 16px'
      }
    },
    // 结算数量
    submitBtn () {
      const count = this.selectedGoodsCount
      return '结算' + (count ? `(${count})` : '')
    },
     // 计算shopCart的数量
    totalCount () {
      return Object.keys(this.shopCart).length
    },
    // 1.是否显示空购物车样式
    isShowEmptyCart () {
      return this.totalCount > 0 ? true : false
    },
    // 2.延展出store里的shopCart的数据
    ...mapGetters({
      selectedGoodsCount: 'SELECTED_GOODS_COUNT',
      totalPrice: 'SELECTED_GOODS_PRICE',
      userInfo: 'userInfo',
      shopCart: 'shopCart'
    }),
    // 5.是否全部选中
    isCheckedAll: {
      get () {
        let tag = this.totalCount > 0
        let shopCart = this.shopCart
        Object.values(shopCart).forEach(goods => {
          if (!goods.checked) {
            tag = false
          }
        })
        return tag
      },
      set (value) {
        // 改变store中的值
        // 解决 assigned to but it has no setter.
        // https://vuex.vuejs.org/zh/guide/forms.html
        //  https://stackoverflow.com/questions/55097118/computed-property-was-assigned-to-but-it-has-no-setter-a-toggle-component
        let isCheckedAll = !value
        this.ALL_SELECT_GOODS({ isCheckedAll })
      }
    }
  },
  methods: {
    // 0.延展mutations中的方法
    ...mapMutations([
      'ADD_GOODS',
      'REDUCE_GOODS',
      'SINGLE_SELECT_GOODS',
      'ALL_SELECT_GOODS',
      'DELETE_SELECT_GOODS',
      'ADD_TO_CART'
    ]),
    // 1.右上角删除
    clearCart () {
      if (this.selectedGoodsCount > 0) {
        this.$dialog.confirm({
          title: '温馨提示',
          message: '确定要删除选中商品吗?'
        }).then(() => {
          // on confirm 确认删除
          this.DELETE_SELECT_GOODS()
        }).catch(() => {
          // on cancel
        })
      }
    },
    // 2.数据加载
    async _initData () {
      let res = await getGuessYouLike()
      if (res.success) {
        this.youLike_product_lists = res.data.product_list
        this.isShowLoading = false
      }
    },
    // 3.减少商品数量
    reduceGoods (goodsID, goodsNum) {
      if (goodsNum > 1) {
        // 3.1 通过goodsID减少商品
        this.REDUCE_GOODS({ goodsID })
      } else if (goodsNum === 1) {
        this.$dialog.confirm({
          title: '温馨提示',
          message: '确定删除该商品吗?'
        }).then(() => {
          // on confirm 确认删除
          this.REDUCE_GOODS({ goodsID })
        }).catch(() => {
          // on cancel
        })
      }
    },
    // 4.增加商品数量 保证传递数据和 mutations 一致
    addGoods (goodsID, goodsName, goodsSmallImage, goodsPrice) {
      this.ADD_GOODS({
        goodsID,
        goodsName,
        goodsSmallImage,
        goodsPrice
      })
    },
    // 5.单个商品的选中和非选中
    single (goodsID) {
      this.SINGLE_SELECT_GOODS({ goodsID })
    },
    // 6.去结算
    onSubmit () {
      // 6.1 当选中商品数量大于0跳转
      if (this.selectedGoodsCount > 0) {
        // 跳转到订单界面
        this.$router.push('/order')
      } else {
        this.$toast({
          message: '请选择商品',
          duration: 1000
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.cart {
  @include setWH(100%, 100%);
  background-color: #f5f5f5;
  .title-wrapper {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 999;
    @include setWH(100%, px2rem(46));
    background: #fff;
    -webkit-background-size: px2rem(2) px2rem(75);
    background-size: px2rem(2) px2rem(75);
    @include flexType(center);
    .clearCart {
      position: absolute;
      right: px2rem(9);
      font-size: px2rem(13);
    }
  }
  .disableClearCart {
    color: grey;
  }
  .cart-wrapper {
    @include setWH(100%, px2rem(1758));
    margin-top: px2rem(46);
    @media screen and (min-width: 300px) and(max-width: 374px) {
      .van-submit-bar {
        bottom: px2rem(56);
      }
    }
    @media screen and (min-width: 375px) and(max-width: 420px) {
      .van-submit-bar {
        bottom: px2rem(46);
      }
    }
    @media screen and (min-width: 420px) and(max-width: 1024px) {
      .van-submit-bar {
        bottom: px2rem(24);
      }
    }
    .emptyCart {
      display: flex;
      flex-direction: column;
      justify-content: center;
      img {
        padding-top: px2rem(35);
        @include setWH(50%, px2rem(175));
        margin: 0 auto;
      }
      .title {
        text-align: center;
        padding: px2rem(7);
      }
      .goHome {
        margin-top: px2rem(35);
        color: #fff;
        background-color: #ff3333;
        text-align: center;
        margin: 0 auto;
        @include setWH(px2rem(105), px2rem(35));
        line-height: px2rem(35);
        border-radius: px2rem(35);
      }
    }
    .contentWrapper {
      padding-top: px2rem(11);
      section {
        background-color: #fff;
        .shopCartListCon {
          @include flexType(center);
          height: px2rem(122);
          border-bottom: px2rem(0.1) solid #e0e0e0;
          margin-bottom: px2rem(12);
          padding-top: px2rem(5);
          .left {
            flex: 1;
            display: flex;
            a {
              display: inline-block;
              margin-top: px2rem(13);
              margin-left: px2rem(8);
            }
            .cartCheckBox {
              background: url("../../assets/img/cart/shop-icon.png") no-repeat;
              background-size: px2rem(42) px2rem(85);
              @include setWH(px2rem(17), px2rem(17));
            }
            .cartCheckBox[checked] {
              background-position: px2rem(-20) 0;
            }
          }
          .center {
            flex: 3;
            img {
              @include setWH(100%, 100%);
            }
          }
          .right {
            flex: 6;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: px2rem(8);
            margin-right: px2rem(8);
            position: relative;
            a {
              height: px2rem(37);
              line-height: px2rem(20);
              overflow: hidden;
              margin-bottom: px2rem(5);
              @include setFontColor(px2rem(13), #000);
            }
          }
        }
        .bottomContent {
          @include flexType(space-between);
          flex-direction: row;
          .shopPrice {
            font-size: px2rem(13);
          }
          .shopDeal span {
            display: inline-block;
            @include setWH(px2rem(17), px2rem(20));
            line-height: px2rem(20);
            text-align: center;
            float: left;
          }
          .shopDeal input {
            float: left;
            @include setWH(px2rem(34),  px2rem(20));
            text-align: center;
            margin: 0 px2rem(3);
            font-size: px2rem(13);
            background-color: #f5f5f5;
            border: 0;
          }
        }
      }
    }
  }
  .van-checkbox {
    margin-left: px2rem(8);
  }
}
</style>
